#!/bin/bash
# 获取真实用户目录
USER_HOME=$(getent passwd ${SUDO_USER:-$USER} 2>/dev/null | cut -d: -f6)
if [[ -z "$USER_HOME" ]]; then
  echo "错误：无法确定用户主目录。"
  exit 1
fi
# 颜色定义 
RED='\033[0;31m' 
GREEN='\033[0;32m' 
YELLOW='\033[33m'
BLUE='\033[0;34m' 
NC='\033[0m' # No Color 
 
# 桌面通知函数 
notify() { 
    local title="$1" 
    local message="$2" 
    local level="$3" 
    local icon="${4:-}"  # 可选参数：图标路径
     
    case "$level" in 
        "success") 
            color="$GREEN" 
            urgency="normal" 
            ;; 
        "warning") 
            color="$BLUE" 
            urgency="normal" 
            ;; 
         "wrong") 
            color="$YELLOW" 
            urgency="normal" 
            ;;              
        "error") 
            color="$RED" 
            urgency="critical" 
            ;; 
        *) 
            color="$NC" 
            urgency="normal" 
            ;; 
    esac 
 
    echo -e "${color}${message}${NC}" 
    # 带图标和不带图标的两种调用方式
    if [[ -n "$icon" ]]; then
        notify-send -u "$urgency" -i "$icon" "$title" "$message" 2>/dev/null || true
    else
        notify-send -u "$urgency" "$title" "$message" 2>/dev/null || true
    fi
} 

# ====开始检测并删除旧备份======
clean_old_backup() {
    local backup_dir="$1"
    if [ -d "$backup_dir" ]; then
        notify "检测到历史备份文件"  "备份文件路径$backup_dir"   "warning"   "/usr/share/icons/hicolor/48x48/apps/wps-optimizer.png"  
        read -p "是否删除历史备份文件？[Yy/N] " confirm
        if [[ $confirm =~ ^[Yy]$ ]]; then
            rm -rf "$backup_dir" && echo -e "${GREEN}已删除旧备份${NC}" || echo -e "${RED}删除失败${NC}"
        fi
    fi
}
# 备份配置文件
backup_config() {
    local config_dir="$1"
    local backup_dir="${config_dir}_bak"
    [ -d "$config_dir" ] && {
        clean_old_backup "${config_dir}_bak"
        mv "$config_dir" "$backup_dir"
        notify "已备份"  "$config_dir → $backup_dir"   "success"   "/usr/share/icons/hicolor/48x48/apps/wps-optimizer.png" 
    }
}
# 清理临时文件
clean_temps() {
    echo -e "${BLUE}正在清理临时文件...${NC}"
    find /tmp -maxdepth 1 $ -name "wps*" -o -name "kingsoft*" $ -exec rm -rfv {} \; 2>/dev/null
}
# 主流程
echo -e "${BLUE}🔍 正在优化WPS性能，请稍候...${NC}"
backup_config "$USER_HOME/.config/Kingsoft"
backup_config "$USER_HOME/.config/kingsoft" 
backup_config "$USER_HOME/.cache/Kingsoft"
backup_config "$USER_HOME/.cache/wps"
backup_config "$USER_HOME/.local/share/Kingsoft"
clean_temps

notify "✅ 优化完成"  "建议重启WPS以获得最佳效果"   "success"   "/usr/share/icons/hicolor/48x48/apps/wps-optimizer.png" 
echo  -e "\n${GREEN}感谢您使用本软件，软件免费使用与更新，具体软件更新请访问以下网址：https://gitee.com/seeker_ok/wps-optimizer${NC}"
read -p "$(echo -e ${BLUE}按任意键关闭此窗口...${NC})" 
